/*
 * SqliteStore.cpp
 *
 *  Created on: 2017年3月9日
 *      Author: chuanjiang.zh
 */

#include "SqliteStore.h"
#include "CLog.h"


int SqliteStore::callback(void * /*NotUsed*/, int argc, char **argv, char **azColName)
{
    int i;
    for(i=0; i<argc; i++){
        printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
    }
    printf("\n");
    return 0;
}


SqliteStore::SqliteStore():
	m_sqlite()
{
}

SqliteStore::~SqliteStore()
{
	close();
}

bool SqliteStore::open(const std::string& path)
{
    sqlite3_open(path.c_str(), &m_sqlite);
    if (m_sqlite)
    {
    }

    return (m_sqlite != NULL);
}

void SqliteStore::close()
{
    if (isOpen())
    {
        sqlite3_close(m_sqlite);
        m_sqlite = NULL;
    }
}

bool SqliteStore::isOpen()
{
	return (m_sqlite != NULL);
}

sqlite3* SqliteStore::get()
{
	return m_sqlite;
}



bool SqliteStore::execute(const std::string& sql)
{
    if (!m_sqlite)
    {
        return false;
    }

    bool done = false;
    char *zErrMsg = 0;
    int rc = sqlite3_exec(m_sqlite, sql.c_str(), callback, NULL, &zErrMsg);
    if( rc != SQLITE_OK )
    {
    	CLog::warning("SqliteStore::execute. %s\n", zErrMsg);
    	sqlite3_free(zErrMsg);
    }
    else
    {
        done = true;
    }
    return done;
}

int SqliteStore::queryInt(const std::string& sql, int defValue)
{
    if (!m_sqlite)
    {
        return defValue;
    }

    sqlite3_stmt *stmt;
    int rc = sqlite3_prepare_v2(m_sqlite, sql.c_str(), -1, &stmt, NULL);
    if (rc != SQLITE_OK)
    {
        return defValue;
    }

    int value = defValue;
    rc = sqlite3_step(stmt);
    if (rc == SQLITE_ROW)
    {
        value = sqlite3_column_int(stmt, 0);
    }

    sqlite3_finalize(stmt);

    return value;
}

bool SqliteStore::queryString(const std::string& sql, std::string& value)
{
	if (!m_sqlite)
	{
		return false;
	}

	sqlite3_stmt *stmt;
	int rc = sqlite3_prepare_v2(m_sqlite, sql.c_str(), -1, &stmt, NULL);
	if (rc != SQLITE_OK)
	{
		return false;
	}

	bool found = false;
	rc = sqlite3_step(stmt);
	if (rc == SQLITE_ROW)
	{
		value = (const char*)sqlite3_column_text(stmt, 0);
		found = true;
	}

	sqlite3_finalize(stmt);

	return found;
}

bool SqliteStore::insert(const std::string& sql, int& autoId)
{
	bool ret = execute(sql);
	autoId = (int)sqlite3_last_insert_rowid(m_sqlite);
	return ret;
}

bool SqliteStore::insert(const std::string& sql, int64_t& autoId)
{
	bool ret = execute(sql);
	autoId = sqlite3_last_insert_rowid(m_sqlite);
	return ret;
}
